//
//  XQLocationManager.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/2/16.
//

import UIKit
import CoreLocation

class XQLocationManager: NSObject {
    
    static let shared = XQLocationManager()
    
    private override init() {}
    
    public var placemark : CLPlacemark?
    
    public var location : CLLocation?
    
    private lazy var locationManager : CLLocationManager = {
        let manager = CLLocationManager()
        manager.delegate = self
        manager.requestAlwaysAuthorization()
        manager.distanceFilter = 0.01
        manager.desiredAccuracy = kCLLocationAccuracyBest
        return manager
    }()
    
    func startLocation() {
        self.locationManager.stopUpdatingLocation()
        self.locationManager.startUpdatingLocation()
    }
}

extension XQLocationManager : CLLocationManagerDelegate{
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        
        manager.startUpdatingLocation()
        
        guard let location = locations.last else { return }
        
        self.location = location
                
        let geocoder = CLGeocoder()
        geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
            if let error = error {
                print("Geocoding error: \(error)")
                return
            }
            
            if let placemark = placemarks?.first {
                self.placemark = placemark
            }
            
            XQAnalysisManager.shared.notifyLocation()
        }
    }
}

extension XQLocationManager {
    public func locationInfo() -> [String : String] {
        guard let pl = self.placemark,let lo = self.location else {return [:]}
        
        let country : String = pl.country ?? ""
        let administrativeArea : String = pl.administrativeArea ?? ""
        let locality : String = pl.locality ?? ""
        let subLocality : String = pl.subLocality ?? ""
        let thoroughfare : String = pl.thoroughfare ?? ""
        let isoCountryCode : String = pl.isoCountryCode ?? ""
        let latitude = lo.coordinate.latitude == 0 ? "0" : String(format: "%.6f", lo.coordinate.latitude)
        let longitude = lo.coordinate.longitude == 0 ? "0" : String(format: "%.6f", lo.coordinate.longitude)
        
        return [
            "lost" : administrativeArea,
            "team" : isoCountryCode,
            "favorite" : country,
            "particular" : thoroughfare,
            "sentences" : latitude,
            "longer" : longitude,
            "probation" : locality,
            "opposed" : subLocality,
        ]
    }
}
